package xin.cymall.service.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.cymall.common.exception.MyException;
import xin.cymall.dao.UserDao;
import xin.cymall.entity.User;
import xin.cymall.service.UserService;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	
	@Override
	public User queryObject(String userId){
		return userDao.queryObject(userId);
	}
	
	@Override
	public List<User> queryList(Map<String, Object> map){
		return userDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return userDao.queryTotal(map);
	}
	
	@Override
	public void save(String username,String mobile, String password){
		User old=userDao.queryByUsername(username);
		if(old!=null){
			throw new MyException("用户名已存在");
		}
		User user = new User();
		user.setMobile(mobile);
		user.setUsername(username);
		user.setPassword(DigestUtils.sha256Hex(password));
		user.setCreateTime(new Date());
		userDao.save(user);
	}
	
	@Override
	public void update(User user){
		userDao.update(user);
	}
	
	@Override
	public void delete(Long userId){
		userDao.delete(userId);
	}
	
	@Override
	public void deleteBatch(Long[] userIds){
		userDao.deleteBatch(userIds);
	}


	public User queryByUsername(String username) {
		return userDao.queryByUsername(username);
	}

	@Override
	public String login(String username, String password) {
		User user = queryByUsername(username);

		//密码错误
		if(user==null||!user.getPassword().equals(DigestUtils.sha256Hex(password))){
			throw new MyException("用户名或密码错误");
		}

		return user.getUserId();
	}

}
